package mathy.wili.misc;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import mathy.c.Ca;
/**
 * 	用来统计各个名称下的【计时次数、总耗时】。
 * @author weila 2021-2-3
 */
public class Time9 {
	private static boolean disabled = false;

	private static Time9 INST = new Time9();

	/**
	 * name ~>[times, cost, lastStartTime, depth,status]
	 */
	static Map<Object, long[]> costMap = new ConcurrentHashMap<Object, long[]>();
	public static Time9 time(int start, Object name) {
		return time(start, 0, name);
	}

	/**
	 * 	启动/暂停 给定名称的计时器（支持函数的递归调用）。 
	 */
	public static Time9 time(int start, int depth, Object name) {
		if (disabled)
			return INST;
		/* 
			函数若存在递归调用，为了在计时的起止上相呼应，同名计时器当起止于相同的深度。
			这使得对 fun的调用当不重复计算其递归调用。 
		 */
		if (++inc == 23)
			Ca.pause();
		if (start == 1) {
			if (name.equals("jarFileOrClassRootOf"))
				Ca.pause();
			long[] cost = costMap.get(name);
			if (cost == null) {
				costMap.put(name, cost = new long[] { 1, 0, System.currentTimeMillis(), depth, 1 });
			} else {
				if (depth >= 0) {
					if (cost[3] != depth)
						return INST;//不应统计递归调用
					if (cost[4] != 0)
						Ca.asert(false, depth, ":" + name, ",Start already.");
				}
				cost[4] = 1;
				cost[0]++;
				cost[2] = System.currentTimeMillis();
			}
		} else {
			long[] cost = costMap.get(name);
			if (depth >= 0) {
				if (cost[3] != depth)
					return INST;//不应统计递归调用
				if (cost[4] != 1)
					Ca.asert(false, depth, ":" + name, ",Stop already.");
			}
			cost[4] = 0;
			cost[1] += System.currentTimeMillis() - cost[2];
		}
		return INST;
	}
	static int inc;
}
